<template>
  <div class="requisition-pool-wrap table-gl-w">
    <div class="left">
      <ul>
        <li v-for="(item, i) in settleTypeList" :key="i" @click="changeSettleType(item)" :class="{ active: searchVal.settleType === item.val }">{{ item.name }}</li>
      </ul>
    </div>
    <div class="right">
      <a-tabs @change="changeStatus" v-model:active-key="searchVal.requestStatus" size="mini">
        <a-tab-pane key="" title="全部" />
        <a-tab-pane v-for="tab in Object.values(tabsMap)" :key="tab.key" :title="tab.title" />
      </a-tabs>

      <div class="search-w table-filter-form">
        <FilterTable v-if="searchVal.settleType === 1" :filterItem="filterItem1" :isReset="true" @search="searchByVal" />
        <FilterTable v-else :filterItem="filterItem2" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getTableList">
          <template #headerLeft>
            <p style="color: #999"> <icon-info-circle class="warningColor" />请款池按照采购单的结算方式获取单据，结算方式为【现结】采购单状态=待交货才进入到请款池，结算方式为【月结】 交货单状态=已入库才进入到请款池。 </p>
            <a-button type="primary" size="medium" @click="openAddBill" v-if="$authPass('finance.payment.order.add')">批量请款</a-button>
          </template>
          <template #tableBody>
            <a-table
              class="table-two-line show-border-table"
              ref="tableRef"
              row-key="id"
              :summary="true"
              :loading="tableLoading"
              @sorter-change="sorterChange"
              @selection-change="selectColumn"
              :row-selection="rowSelection"
              :data="tableList"
              :scroll="{
                x: '100%',
                y: '100%',
              }"
              size="mini"
              :pagination="false"
            >
              <template #columns>
                <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                  <template #cell="{ rowIndex }">
                    <p>{{ rowIndex + 1 }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="供应商" :width="130" fixed="left">
                  <template #cell="{ record }">
                    <TextLimit :rows="1" :val="record.supplierName" />
                    <p style="color: #999">{{ record.supplierCode }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="交货单号" :width="110" fixed="left" v-if="searchVal.settleType === 2">
                  <template #cell="{ record }">
                    <a-space :size="4">
                      <p class="highlight">{{ record.deliveryNo || '--' }}</p>
                      <CopyText :val="record.deliveryNo" class="popup-edit-icon-hover" />
                    </a-space>
                    <p style="color: #999">{{ deliveryStatusMap[record.deliveryStatus] }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="采购单号" :width="110" fixed="left">
                  <template #cell="{ record }">
                    <a-space :size="4">
                      <p class="highlight">{{ record.purchaseNo || '--' }}</p>
                      <CopyText :val="record.purchaseNo" class="popup-edit-icon-hover" />
                    </a-space>
                    <p style="color: #999">{{ purchaseStatusMap[record.purchaseStatus] }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="付款状态" :width="80">
                  <template #cell="{ record }">
                    <p>{{ payStatusMap[record.paymentStatus] }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="请款状态" :width="80">
                  <template #cell="{ record }">
                    <p>{{ tabsMap[record.requestStatus] ? tabsMap[record.requestStatus].title : record.requestStatus }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="purchaseAmt" :width="75" v-if="searchVal.settleType === 1">
                  <template #title>
                    <a-popover content="本采购单的采购数量 减去 截单数量">
                      <p>
                        <span>采购数</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                </a-table-column>
                <a-table-column data-index="deliveryAmt" :width="75">
                  <template #title>
                    <a-popover content="该交货单的交货数量">
                      <p>
                        <span>交货数</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                </a-table-column>
                <a-table-column data-index="warehouseAmt" :width="80">
                  <template #title>
                    <a-popover content="该交货单的实际入库数量">
                      <p>
                        <span>已入库数</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                </a-table-column>
                <a-table-column data-index="purchaseAmount" :width="120" v-if="searchVal.settleType === 1">
                  <template #title>
                    <a-popover content="采购数量X单价">
                      <p>
                        <span>采购金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>含税：￥{{ record.purchaseAmount }}</p>
                    <p>税额：￥{{ record.purchaseTaxAmount }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="deliveryAmount" :width="120" v-if="searchVal.settleType === 2">
                  <template #title>
                    <a-popover content="交货金额=交货数量X单价">
                      <p>
                        <span>交货金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>含税：￥{{ record.deliveryAmount }}</p>
                    <p>税额：￥{{ record.deliveryTaxAmount }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="inventoryAmount" :width="120">
                  <template #title>
                    <a-popover content="到货金额=实际入库数量X单价">
                      <p>
                        <span>到货金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>含税：￥{{ record.inventoryAmount }}</p>
                    <p>税额：￥{{ record.inventoryTaxAmount }}</p>
                  </template>
                </a-table-column>

                <a-table-column data-index="paidAmount" :width="100">
                  <template #title>
                    <a-popover content="已完成支付的请款单金额">
                      <p>
                        <span>已付金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>￥{{ record.paidAmount }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="unpaidAmount" :width="100">
                  <template #title>
                    <a-popover content="未支付金额=到货金额-已支付金额">
                      <p>
                        <span>未付金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>￥{{ record.unpaidAmount }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="requestAmount" :width="100">
                  <template #title>
                    <a-popover content="请款中金额=请款单状态为待支付">
                      <p>
                        <span>请款中金额</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template #cell="{ record }">
                    <p>￥{{ record.requestAmount }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="gmtBillCreate" title="单据创建时间" :sortable="sortable" :width="120">
                  <template #cell="{ record }">
                    <p>{{ $setTime(record.gmtBillCreate, 'YYYY-MM-DD HH:mm') }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="gmtBillSign" title="交货签收时间" :sortable="sortable" :width="120" v-if="searchVal.settleType === 2">
                  <template #cell="{ record }">
                    <p>{{ $setTime(record.gmtBillSign, 'YYYY-MM-DD HH:mm') }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="purchaseUname" title="采购员" :width="70" />
                <a-table-column data-index="signUname" title="交货单签收人" :width="100" v-if="searchVal.settleType === 2" />

                <a-table-column title="备注" :width="120">
                  <template #cell="{ record }">
                    <a-space>
                      <TextLimit :val="record.remark || '--'" />
                      <icon-edit v-if="$authPass('finance.payment.pool.update')" @click="openEditRemarkDialog(record)" class="cursor popup-edit-icon-hover" />
                    </a-space>
                  </template>
                </a-table-column>

                <a-table-column title="操作" :width="110" fixed="right">
                  <template #cell="{ record }">
                    <a-space>
                      <a-button v-if="(record.requestStatus == 10 || record.requestStatus == 20) && $authPass('finance.payment.order.add')" type="text" @click="openAddBill(record)">请款</a-button>
                      <a-button v-if="record.requestStatus == 10 && $authPass('finance.payment.pool.close')" type="text" @click="openEndDialog(record)">结束请款</a-button>
                      <a-button v-if="record.requestStatus == 40 && $authPass('finance.payment.pool.again')" type="text" @click="openAgainDialog(record)">重新请款</a-button>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
              <template #summary-cell="{ column }">
                <p v-if="column.dataIndex == 'sort'">合计</p>
                <p v-else-if="['purchaseAmt', 'deliveryAmt', 'warehouseAmt'].includes(column.dataIndex)">{{ countMap[column.dataIndex] }}</p>
                <p v-else-if="['paidAmount', 'unpaidAmount', 'requestAmount'].includes(column.dataIndex)">￥{{ Number(countMap[column.dataIndex] || 0).toFixed(2) }}</p>
                <div v-else-if="['deliveryAmount'].includes(column.dataIndex)">
                  <p>含税：￥{{ countMap.deliveryAmount }}</p>
                  <p>税额：￥{{ countMap.deliveryTaxAmount }}</p>
                </div>
                <div v-else-if="['purchaseAmount'].includes(column.dataIndex)">
                  <p>含税：￥{{ countMap.purchaseAmount }}</p>
                  <p>税额：￥{{ countMap.purchaseTaxAmount }}</p>
                </div>
                <div v-else-if="['inventoryAmount'].includes(column.dataIndex)">
                  <p>含税：￥{{ countMap.inventoryAmount }}</p>
                  <p>税额：￥{{ countMap.inventoryTaxAmount }}</p>
                </div>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
  </div>
  <!-- 编辑备注 -->
  <a-modal :width="600" v-model:visible="showEditRemarkDialog" :ok-loading="submitLoading" title="备注" title-align="start" :mask-closable="false" @cancel="editRemarkVal = null" :on-before-ok="submitRemark">
    <a-textarea placeholder="输入备注" style="height: 100px" v-model="editRemarkVal" />
  </a-modal>
  <!-- 结束请款 -->
  <a-modal :width="600" v-model:visible="showEndDialog" :ok-loading="submitLoading" :title="`结束款单-货款${currentData.settleType === 1 ? '现结' : '月结'}`" title-align="start" :mask-closable="false" :on-before-ok="submitEnd">
    <p style="font-size: 16px">
      确定将采购单
      <span class="highlight" style="margin: 0 5px">{{ currentData.purchaseNo }}</span>
      结束请款？
    </p>
    <p style="color: #999">结束请款之后，该采购单进入到已结束请款池，如需继续请款，可以从中移出。</p>
  </a-modal>
  <!-- 重新请款 -->
  <a-modal :width="600" v-model:visible="showAgainDialog" :ok-loading="submitLoading" :title="`继续款单-货款${currentData.settleType === 1 ? '现结' : '月结'}`" title-align="start" :mask-closable="false" :on-before-ok="submitAgain">
    <p style="font-size: 16px">
      确定将采购单
      <span class="highlight" style="margin: 0 5px">{{ currentData.purchaseNo }}</span>
      继续请款？
    </p>
    <p style="color: #999">继续请款将移入到未请款池。</p>
  </a-modal>
  <!-- 创建请款单 -->
  <AddPayrollRequisition v-if="shopAddBill" :settleType="searchVal.settleType" :list="selectRows" :isShow="shopAddBill" @closed="shopAddBill = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message } from '@arco-design/web-vue'
  import { findSupperList, findPaymentPoolPage, findPaymentPoolSum, updatePaymentPoolRemark, closePaymentPoolRequest, againPaymentPoolRequest } from '@/api/purchase'
  import AddPayrollRequisition from './components/addPayrollRequisition.vue'

  onMounted(() => {
    getTableList()
    getSupplierList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    requestStatus: '',
    settleType: 1,
  })
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const filterItem1 = ref<Array<FilterTableItem>>([
    {
      key: 'supplierId',
      label: '供应商',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
    },
    {
      type: 'input_search',
      key: 'purchaseNo',
      value: ref(),
      label: '采购单号',
      width: 160,
    },
    {
      key: 'paymentStatus',
      label: '付款状态',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '未付款',
          value: 10,
        },
        {
          label: '部分付款',
          value: 20,
        },
        {
          label: '已付款',
          value: 30,
        },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtBillCreate',
      keyItems: [{ label: '创建时间', value: 'gmtBillCreate' }],
      keyWidth: 100,
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const filterItem2 = ref<Array<FilterTableItem>>([
    {
      key: 'supplierId',
      label: '供应商',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
    },
    {
      type: 'input_search',
      key: 'purchaseNo',
      value: ref(),
      label: '采购单号',
      width: 160,
    },
    {
      type: 'input_search',
      key: 'deliveryNo',
      value: ref(),
      label: '交货单号',
      width: 160,
    },
    {
      key: 'paymentStatus',
      label: '付款状态',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '未付款',
          value: 10,
        },
        {
          label: '部分付款',
          value: 20,
        },
        {
          label: '已付款',
          value: 30,
        },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtBillCreate',
      keyItems: [
        { label: '单据创建时间', value: 'gmtBillCreate' },
        { label: '交货签收时间', value: 'gmtBillSign' },
      ],
      keyWidth: '140',
      value: ref(),
      placeholder: '请输入',
      label: '单据创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const purchaseStatusMap = {
    0: '已作废',
    1: '草稿中',
    10: '待审核',
    20: '待接单',
    30: '待交货',
    40: '交货中',
    50: '已交货',
    60: '已完成',
    61: '已截单',
  }
  const deliveryStatusMap = {
    0: '已作废',
    10: '待配货',
    20: '待出库',
    30: '待签收',
    40: '待入库',
    50: '入库中',
    60: '已入库',
  }
  const payStatusMap = {
    10: '未付款',
    20: '部分付款',
    30: '已付款',
  }
  const tabsMap = {
    10: { key: 10, title: '未请款' },
    20: { key: 20, title: '部分请款' },
    30: { key: 30, title: '已请款' },
    40: { key: 40, title: '已结束请款' },
  }
  const settleTypeList = [
    { name: '货款现结', val: 1 },
    { name: '货款月结', val: 2 },
  ]

  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectRows = ref<Array<any>>([])
  const selectIds = ref([])
  const tableRef = ref()
  const countMap = ref<any>({})
  const submitLoading = ref(false)
  const shopAddBill = ref(false)

  const showEditRemarkDialog = ref(false)
  const showEndDialog = ref(false)
  const showAgainDialog = ref(false)
  const editRemarkVal = ref()
  const currentData = ref<any>({})

  let filterData = {}
  let tableListMap = {}

  //供应商列表
  async function getSupplierList() {
    const res: any = await findSupperList()
    let optionItem = res?.data?.map((el: any) => {
      return {
        label: el.supplierName,
        value: el.id,
      }
    })
    filterItem1.value[0].optionItems = optionItem
    filterItem2.value[0].optionItems = optionItem
  }

  // 切换结算类型
  function changeSettleType(item: any) {
    if (searchVal.value.settleType === item.val) return
    searchVal.value.settleType = item.val
    searchVal.value.pageNum = 1
    searchVal.value.requestStatus = ''
    filterData = {}
    getTableList()
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.requestStatus = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.sortField = null
      searchVal.value.sortType = null
    } else {
      searchVal.value.sortField = dataIndex
      searchVal.value.sortType = direction == 'ascend' ? 1 : -1
    }
    getTableList()
  }

  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 查询合计
  async function getCountList(params: any) {
    const res: any = await findPaymentPoolSum(params)
    countMap.value = res?.data || {}
  }
  // 获取列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData,
    }
    tableLoading.value = true
    const res: any = await findPaymentPoolPage(params)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap = {}
    tableList.value.forEach((el: any) => {
      tableListMap[el.id] = el
    })
    getCountList(params)
  }
  // 打卡编辑备注
  function openEditRemarkDialog(row: any) {
    currentData.value = row
    showEditRemarkDialog.value = true
  }
  // 编辑备注
  async function submitRemark() {
    const res: any = await updatePaymentPoolRemark({
      ids: [currentData.value.id],
      remark: editRemarkVal.value,
    })
    if (!res) return false
    Message.success('修改备注成功')
    getTableList()
  }
  // 打开结束请款弹窗
  function openEndDialog(row: any) {
    currentData.value = row
    showEndDialog.value = true
  }
  // 结束货款
  async function submitEnd() {
    const res: any = await closePaymentPoolRequest({
      ids: [currentData.value.id],
    })
    if (!res) return false
    Message.success('该单据已结束请款')
    getTableList()
  }
  // 打开继续请款弹窗
  function openAgainDialog(row: any) {
    currentData.value = row
    showAgainDialog.value = true
  }
  // 结束货款
  async function submitAgain() {
    const res: any = await againPaymentPoolRequest({
      ids: [currentData.value.id],
    })
    if (!res) return false
    Message.success('该单据重新请款')
    getTableList()
  }

  // 请款
  function openAddBill(row?: any) {
    if (row?.id) {
      selectRows.value = [row]
    } else {
      selectRows.value = []
      selectIds.value.map((id) => {
        let _data = tableListMap[id]
        if (_data.requestStatus === 10 || _data.requestStatus === 20) {
          selectRows.value.push(_data)
        }
      })
    }
    if (!selectRows.value.length) {
      Message.error('请最少选择一个未请款或部分请款的单据')
      return
    }
    shopAddBill.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .requisition-pool-wrap {
    height: calc(100vh - @headerHeight - @tabviewHeight);
    display: flex;
    flex-direction: row;
  }
  .left {
    width: 160px;
    height: 100%;
    background-color: #fff;
    margin-right: 5px;
    padding: 20px 10px;
    li {
      line-height: 36px;
      text-align: center;
      background-color: #fff;
      border-right: 2px solid #fff;
      cursor: pointer;
      &.active {
        background-color: rgb(var(--primary-1));
        border-color: rgb(var(--primary-6));
      }
    }
  }
  .right {
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: hidden;
  }
</style>
